package com.example.wifimonitor;

import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private WifiReceiver wifiReceiver;
    private TextView statusTextView;
    private ListView wifiLogListView;
    private ArrayAdapter<String> logAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        statusTextView = findViewById(R.id.statusTextView);
        wifiLogListView = findViewById(R.id.wifiLogListView);
        WifiLog.initialize(this); // Initialize WifiLog with context
        
        // 初始化日志适配器
        logAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, WifiLog.getLogs());
        wifiLogListView.setAdapter(logAdapter);
        
        // 初始化WiFi接收器
        wifiReceiver = new WifiReceiver();
        
        // 显示当前状态
        updateStatus();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 注册WiFi状态变化的广播接收器
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        registerReceiver(wifiReceiver, intentFilter);
        
        // 更新状态显示
        updateStatus();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消注册广播接收器
        unregisterReceiver(wifiReceiver);
    }
    
    // 更新WiFi状态显示
    public void updateStatus() {
        // 更新日志列表
        logAdapter.clear();
        logAdapter.addAll(WifiLog.getLogs());
        logAdapter.notifyDataSetChanged();
        
        // 更新WiFi状态
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        if (wifiManager != null) {
            if (wifiManager.isWifiEnabled()) {
                statusTextView.setText("WiFi状态: 已开启");
            } else {
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                    statusTextView.setText("WiFi状态: 已关闭 (请在设置中开启)");
                } else {
                    statusTextView.setText("WiFi状态: 已关闭 (将自动重新开启)");
                }
            }
        }
    }
    
    // 显示提示信息
    public void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}